package com.hencoder.hencoderpracticedraw1.practice;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

public class Practice10HistogramView extends View {

    public Practice10HistogramView(Context context) {
        super(context);
    }

    public Practice10HistogramView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public Practice10HistogramView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

//        综合练习
//        练习内容：使用各种 Canvas.drawXXX() 方法画直方图
        myDraw(canvas);
        drawText(canvas);
        drawSmallText(canvas);
    }

    private void myDraw(Canvas canvas) {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.WHITE);
        paint.setStrokeWidth(2);

        Path path = new Path();
        path.moveTo(130, 100);
        path.lineTo(130, 500);
        path.rLineTo(830, 0);

        canvas.drawPath(path, paint);
    }

    private void drawText(Canvas canvas) {
        String title = "直方图";
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.WHITE);
        paint.setTextSize(45);
        int currentWith = getWidth() / 2 - getTextWith(paint, title) / 2;
        canvas.drawText(title, currentWith, 620, paint);
    }

    private int getTextWith(Paint paint, String str) {
        Rect rect = new Rect();
        paint.getTextBounds(str, 0, str.length(), rect);
        int w = rect.width();
        int h = rect.height();
        return w;
    }

    String[] text = {"Froyo", "GB", "LCS", "JB", "KitKat", "L", "M"};
    Float[] hight = {2f, 20f, 20f, 200f, 400f, 500f, 50f};

    private void drawSmallText(Canvas canvas) {
        Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setColor(Color.WHITE);
        textPaint.setTextSize(25);

        for (int i = 0; i < text.length; i++) {
            float currentSpace = i * 120;
            canvas.drawText(text[i], 195 - getTextWith(textPaint, text[i]) / 2 + currentSpace, 522, textPaint);
        }

        textPaint.setColor(0xFF72B916);
        textPaint.setStyle(Paint.Style.FILL);
        /**
         * 左上右下
         */

        for (int i = 0; i < hight.length; i++) {
            float currentSpace = i * 120;
            canvas.drawRect(158+ currentSpace, 500 - hight[i], 240+ currentSpace, 500, textPaint);
        }
    }
}
